package com.kun.kunnmall.secikll.scheduled;

import com.kun.kunnmall.secikll.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架服务
 * 每天晚上3点：上架最近三天需要秒杀的商品
 * 当天00:00:00 - 23:59:59
 * 明天00:00:00 - 23:59:59
 * 后天00:00:00 - 23:59:59
 */
@Service
@Slf4j
public class SeckillSkuScheduled {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    private final String UPLOAD_LOCK = "seckill:upload:lock";

    // TODO 上架应该做成一个幂等性的操作，上架过的商品无需再次上架
    @Scheduled(cron = "* * * * * ?")
    @Async
    public void uploadSeckillSkuLatest3Days() {
        // 1. 重复上架无需处理，因为前几天已经上架过了
        log.info("上架秒杀的商品");
        // 2. 假设有多台服务器同时执行秒杀商品的上架服务，只需要一个执行成功，我们可以加分布式锁
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        try {
            lock.lock(10, TimeUnit.SECONDS);
            seckillService.uploadSeckillSkuLatest3Days();
        } finally {
            lock.unlock();
        }


    }
}
